from .ess import dountil as _dountil
from os import makedirs as _makedirs
from os.path import splitext as _splitext, isdir as _isdir, exists as _exists
from json import loads as _loads
codes: list = ["utf-8", "gbk"]


def AdSlash(fp: str) -> str:
    if fp == '':
        return fp
    return fp if fp[-1] == '\\' else fp+'\\'


def CbFName(fn, n):
    return _splitext(fn)[0]+'('+str(n)+')'+_splitext(fn)[1]


runfile = lambda fp, c="utf-8": exec(fread(fp, c), globals())


def changeCode(fp: str, code: str = "gbk"):
    """改变文件的编码"""
    temp = fread(fp)
    with open(fp, mode='w', encoding=code) as f:
        o = f.write(temp)
    return o


def mkfold(dirName: str) -> None:
    """创造文件夹"""
    return None if _isdir(dirName) else _makedirs(dirName)


def fread(fp: str) -> str:
    """打开文件，返回文本内容"""
    for code in codes:
        try:
            with open(fp, mode='r', encoding=code) as f:
                o = f.read()
                break
        except:
            continue
    return o


def bfread(fp: str) -> bytes:
    """打开文件，返回二进制内容"""
    with open(fp, mode="rb") as f:
        o = f.read()
    return o


def freadl(fp: str) -> list:
    """打开文件，返回各行作为列表元素"""
    for code in codes:
        try:
            with open(fp, mode='r', encoding=code) as f:
                o = f.readlines()
                break
        except:
            continue
    return o


def fwrite(fp: str, cont: str) -> int:
    """写入文件"""
    with open(fp, mode='w', encoding="utf-8") as f:
        o = f.write(cont)
    return o


def newfname(fn: str) -> str:
    if not _exists(fn):
        return fn
    else:
        return CbFName(fn, _dountil(lambda n: not _exists(CbFName(fn, n)), lambda x: (x+1,), 1)[0])


def jsonRead(fp: str):
    """读JSON文件"""
    return _loads(fread(fp))
